package com.wsoft.hr.pm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.wsoft.bpm.enums.ApproveStatus;
import com.wsoft.constant.CommonConstant;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.entity.BaseEntity;
import com.wsoft.hr.pm.entity.HrPmActivityEntity;
import com.wsoft.hr.pm.entity.HrPmCycleEntity;
import com.wsoft.hr.pm.entity.HrPmMemberTemplateEntity;
import com.wsoft.hr.pm.entity.HrPmWarningEntity;
import com.wsoft.hr.pm.enums.WarningTypeEnum;
import com.wsoft.hr.pm.manager.HrPmActivityManager;
import com.wsoft.hr.pm.manager.HrPmCycleManager;
import com.wsoft.hr.pm.manager.HrPmMemberTemplateManager;
import com.wsoft.hr.pm.manager.HrPmWarningManager;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程阻断预警 - 次月考核指标
 *
 * @Author z001
 * @Date 2025/3/8 08:57
 */
@Service
public class MemberTemplateJob implements Job {
    @Resource
    private HrPmCycleManager cycleManager;
    @Resource
    private HrPmActivityManager activityManager;
    @Resource
    private HrPmMemberTemplateManager memberTemplateManager;
    @Resource
    private HrPmWarningManager warningManager;
    @Resource
    private CommonFreemarkerService freemarkerService;
    /**
     * 模版code
     */
    private final String FREEMARKER_CODE = "freemarker_code";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail job = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = job.getJobDataMap();
        //任务参数
        Object jobParam = jobDataMap.get(CommonConstant.JOB_PARAMS);
        if (ObjUtil.isNull(jobParam)) {
            return;
        }
        JSONObject param = JSONObject.parseObject(jobParam.toString());
        //获取模版code
        Object freemarkerCode = param.get(FREEMARKER_CODE);
        if (null == freemarkerCode) {
            return;
        }

        String nextMonth = getNextMonthDate();
        //获取下个月的周期
        List<HrPmCycleEntity> cycleEntities = cycleManager.likeExpireDate(nextMonth);
        if (CollUtil.isEmpty(cycleEntities)) {
            return;
        }
        //判断下个月周期中有没有活动,没有则预警
        List<Long> cycleIdList = cycleEntities.stream().map(BaseEntity::getId).collect(Collectors.toList());

        List<HrPmActivityEntity> entities = activityManager.listByCyclesNotStatus(cycleIdList, ApproveStatus.APPROVED.getValue());
        if (CollUtil.isNotEmpty(entities)) {
            //活动id
            List<Long> activityIdList = entities.stream().map(BaseEntity::getId).collect(Collectors.toList());
            List<HrPmMemberTemplateEntity> list = memberTemplateManager.listByActivityIds(activityIdList, ApproveStatus.APPROVED.getValue());
            if (CollUtil.isEmpty(list)) {
                return;
            }
            List<HrPmWarningEntity> warningList = new ArrayList<>();
            for (HrPmMemberTemplateEntity entity : list) {
                HrPmWarningEntity warning = new HrPmWarningEntity();
                warning.setTitle(buildFreemarkerMap(entity,nextMonth,freemarkerCode));
                warning.setType(WarningTypeEnum.PROCESS_BLOCKAGE.getType());
                warning.setHrOrgId(entity.getHrOrgId());
                warning.setOpenType("component");
                warning.setOpenPage("");
                warningList.add(warning);
            }
            warningManager.saveBatch(warningList);


        }

    }

    /**
     * 构建freemarker模板
     * @param vo
     * @param freemarkerCode
     * @return
     */
    private String buildFreemarkerMap(HrPmMemberTemplateEntity vo,String nextMonth, Object freemarkerCode){
        Map<String,Object> map = new HashMap<>(3);
        map.put("memberName",vo.getMemberName());
        map.put("nextMonth",nextMonth);
        //${memberName}${nextMonth}月度绩效考核指标尚未指定，即将超时，请及时确认。
        return freemarkerService.sendTextTemplate(freemarkerCode.toString(), map,true);
    }



    /**
     * 获取当前时间的下个月日期，格式为 yyyy-MM
     *
     * @return 下个月的日期，格式为 yyyy-MM
     */
    public static String getNextMonthDate() {
        // 获取当前时间
        Date now = DateUtil.date();

        // 获取下个月的日期
        Date nextMonth = DateUtil.offsetMonth(now, 1);

        // 格式化为 yyyy-MM
        return DateUtil.format(nextMonth, "yyyy-MM");
    }
}
